package com.easy.service.impl;

import com.easy.bean.User;
import com.easy.dao.IUserDao;
import com.easy.service.IUserService;
import com.easy.util.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword;

@Service
public class UserImpl implements IUserService {
    @Autowired
    private IUserDao dao;


    // 修改密码
    @Override
    public boolean updateUser(Integer id, String oldPassword, String newPassword) {
        // 从数据库中获取用户
        User user = dao.getUserById(id);

        // 验证旧密码
        if (user != null && oldPassword!= null &&newPassword !=null
                && DigestUtil.decode(oldPassword, user.getDigest_password())) {
            // 更新新密码
            String newDigestPassword = DigestUtil.randomDigest(newPassword);
            user.setPassword(newPassword);  // 更新密码，实际应用中可以不必要更新此字段
            user.setDigest_password(newDigestPassword);  // 设置新密文
            dao.updateUser(user);
            return true;
        }
        return false;
    }





    @Override
    public User getCurrentUser(String user_name) {
        return dao.getUserByUsername(user_name);
    }


    @Override
    public int editUser(User user) {
        return dao.editUser(user);
    }


    @Override
    public List<User> getUser() {
        return dao.getUser();
    }

    @Override
    public int addUser(User user) {
        return dao.addUser(user);
    }
    @Override
    public int delUser(int id) {
        return dao.delUser(id);
    }

    @Override
    public List<User> getPagedUser(int page, int size) {
        int offset = (page - 1) * size; // 计算 offset
        return dao.getPagedUser(offset, size);
    }
    @Override
    public int getTotalUserCount() {
        return dao.getTotalUserCount();
    }

    @Override
    public List<User> searchUser(String keyword) {
        return dao.searchUser(keyword);
    }
}
